package com.eduService.teacher.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eduService.teacher.entity.EduSubject;
import com.eduService.teacher.entity.excelSubject;
import com.eduService.teacher.service.IEduSubjectService;
import lombok.SneakyThrows;

public class SubjectListener implements ReadListener<excelSubject> {

    private IEduSubjectService subjectService;

    public SubjectListener() { }
    public SubjectListener( IEduSubjectService subjectService) {
        this.subjectService = subjectService;
    }

    @SneakyThrows
    @Override
    public void invoke(excelSubject excelSubject, AnalysisContext analysisContext) {
        if(excelSubject == null){
            throw  new Exception("文件数据为空！");
        }

        EduSubject existFirst = this.isExistFirst(subjectService, excelSubject.getFirstSubjectName());

        if (existFirst == null){
            EduSubject FirstSubject  = new EduSubject();
            FirstSubject.setParentId("0");
            FirstSubject.setTitle(excelSubject.getFirstSubjectName());
            subjectService.save(FirstSubject);
        }
        existFirst = this.isExistFirst(subjectService, excelSubject.getFirstSubjectName());
        System.out.println(existFirst);
        String pid = existFirst.getId();
        System.out.println(pid);
        EduSubject existSecond = this.isExistSecond(subjectService, excelSubject.getSecondSubjectName(), pid);
        if (existSecond == null){
            EduSubject SecondSubject  = new EduSubject();
            SecondSubject.setParentId(pid);
            SecondSubject.setTitle(excelSubject.getSecondSubjectName());
            System.out.println(SecondSubject);
            subjectService.save(SecondSubject);
        }

    }

//    由于核心思想是EasyExcel一行一行地读取数据，并添加到数据，但是在这个过程中
//    一级课程是不能重复添加的
    private EduSubject isExistFirst(IEduSubjectService subjectService,String name){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id","0");
        EduSubject subjectServiceOne = subjectService.getOne(wrapper);
        return subjectServiceOne;
    }

//二级课程不能重复添加
private EduSubject isExistSecond(IEduSubjectService subjectService,String name,String pid){
    QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
    wrapper.eq("title",name);
    wrapper.eq("parent_id",pid);
    EduSubject subjectServiceSecond = subjectService.getOne(wrapper);
    return subjectServiceSecond;
}

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
